package jvs.vfs.sec;

import java.util.List;

import jvs.OS;
import x.java.io.File;

public class Auth {
	private Auth() {}
	
	public static boolean isAuth(File file, String id, AccessControl acl) {
		//local user
		if (acl == null) {
			return true;
		}
		//admin user
		if (OS.isAdminAccessAllowed() && acl.checkGroup(id, AccessControl.ADMIN_GROUP)) {
			return true;
		}
		//
		String path = file.getPath();
		//root
		if (path.equals("/")) {
			return false;
		}
		//
		String[] p = path.split("/", 4);
		// p[0] -> "" 
		String top = p[1];
		if (top.equals("public")) {
			if (OS.isPublicAccessAllowed()) {
				return true;
			}
		}
		//
		if (OS.isBuddyAccessAllowed() == false) {
			return false;
		}
		
		boolean buddy = acl.checkPrincipal(id);
		if (buddy == false) {
			return false;
		}
		// /public
		if (top.equals("public")) {
			return true;
		}
		//shared 
		if (top.equals("shared")) {
			// /shared/  ["", shared]
			if (p.length == 2) {
				return false;
			}
			// /shared/guest
			String sub = p[2];
			if (sub.equals("guest")) {
				return true;
			}
			// /shared/~buddy
			String bfolder = "~"+ id;
			if (sub.equals(bfolder)) {
				return true;
			}
			// /shared/group
			List<Group> groups = acl.getGroups(id);
			if (groups != null && groups.size() > 0) {
				for (Group g: groups) {
					if (g.getName().equals(sub)) {
						return true;
					}
				}
			}
			return false;
		}
		//private
		return false;
	
	}
}
